package com.project.common.utils.bean;

import com.github.pagehelper.Page;
import com.project.common.constant.NumberConstants;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CopyObjectUtils {
    /*
      <!-- javabean copy -->
        <dependency>
            <groupIT>ma.glasnost.orika</groupIT>
            <artifactIT>orika-core</artifactIT>
            <orika.version>1.5.4</orika.version>
        </dependency>

     */

    public static MapperFactory factory = new DefaultMapperFactory.Builder().build();

    /**
     * 全属性复制
     */
    public static <S, T> T copyAtoB(S sourceObject, Class<T> targetClass) {
        return factory.getMapperFacade().map(sourceObject, targetClass);
    }

    /**
     * 非空属性复制
     */
    public static <S, T> T copyAtoBNonNull(S source, T target) {
        if (null == source) {
            return null;
        }
        if (null == target) {
            throw new NullPointerException("target bean is null!");
        }
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
//        factory.getMapperFacade().map(source,target,);
        return target;
    }

    /**
     * 集合数据 拷贝
     */
    public static <S, T> List<T> copyAListToBList(List<S> source, Class<T> targetClass) {
        List<T> targets;
        if (source instanceof Page) {
            targets = new Page<>();
            BeanUtils.copyProperties(source, targets);
        } else {
            targets = new ArrayList<>();
        }
        if (CollectionUtils.isEmpty(source)) {
            return targets;
        }
        factory.getMapperFacade().mapAsCollection(source, targets, targetClass);
        return targets;
    }

    /**
     * 获取对象中 空值的 属性列表
     *
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
